package com.jy.api.service.impl;

import com.jy.api.dao.MemberAccountDao;
import com.jy.api.dao.StoreOrderDao;
import com.jy.api.dao.WechatSendTemplateDao;
import com.jy.api.domain.StoreOrder;
import com.jy.api.domain.WechatSendTemplate;
import com.jy.api.pay.result.PayResult;
import com.jy.api.service.PayService;
import com.jy.api.service.WechatSendTemplateService;
import com.jy.api.signUpReq.admin.SendTemplateSingnUpReq;
import com.jy.api.util.Contens;
import com.jy.api.util.UuidUtil;
import com.jy.api.vo.admin.SendTemplateVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by lihu on 2018/1/17.
 */
@Service
public class WechatSendTemplateServiceImpl implements WechatSendTemplateService {

    @Autowired
    WechatSendTemplateDao wechatSendTemplateDao;

    @Autowired
    MemberAccountDao memberAccountDao;

    @Autowired
    StoreOrderDao storeOrderDao;

    @Autowired
    PayService payService;

    @Override
    @Transactional
    public SendTemplateVo createTemplate(SendTemplateSingnUpReq singnUpReq, String ip) throws Exception {
        WechatSendTemplate sendTemplate = new WechatSendTemplate();
        BeanUtils.copyProperties(singnUpReq, sendTemplate);
        Object o = memberAccountDao.getStoreAllCount(singnUpReq.getStoreId());
        int qty = Integer.parseInt(o.toString());
        int amout = qty * Contens.WECHAT_PRICE;
        StoreOrder storeOrder = new StoreOrder(UuidUtil.getUuid(),
                singnUpReq.getStoreId(), amout, qty, singnUpReq.getId(), ip);
        PayResult payResult = payService.StoreQRCode(storeOrder);
        if (StringUtils.equals(payResult.getStatus(), "0") &&
                StringUtils.equals(payResult.getResultCode(), "0")) {
            storeOrderDao.save(storeOrder);
            wechatSendTemplateDao.save(sendTemplate);
            return new SendTemplateVo(storeOrder.getId(), payResult.getCodeImgUrl());
        }
        return null;
    }
}
